package cn.wit.summit.chwan.utils;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnPageChangeListener;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameTagInfoBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.ui.service.ChWService;
import cn.wit.summit.chwan.ui.service.MyJobIntentService;
import cn.wit.summit.chwan.widgets.NetworkImageHolderView;


/**
 * Created by yangg on 2017/11/15.
 */

public class UtilsMy {
    public static boolean delete(File file) {
        if (file.isFile()) {
            File f = new File(file.getParent() + "/" + System.currentTimeMillis());
            file.renameTo(f);
            try {
                return f.delete();
//                FileUtils.deleteQuietly(f);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return false;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                try {
                    File f = new File(file.getParent() + File.separator + System.currentTimeMillis());
                    file.renameTo(f);
                    return f.delete();
//                    FileUtils.deleteQuietly(f);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            File f = new File(file.getParent() + File.separator + System.currentTimeMillis());
            file.renameTo(f);
            try {
                return f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;

    }

    /**
     * 把文件大小转化为m b,速度
     *
     * @param fileS
     * @return
     */
    public static String FormatFileSizeForSpeed(long fileS) {// 转换文件大小

        DecimalFormat df = new DecimalFormat("#0.0");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }

        if (fileSizeString.equals(".0B") || fileSizeString.equals(".00B")) {
            return "0B";
        }
        return fileSizeString;
    }

    public static String FormatFileSize(long fileS) {// 转换文件大小

        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }

        if (fileSizeString.equals(".0B") || fileSizeString.equals(".00B")) {
            return "0B";
        }
        return fileSizeString;
    }

    public static String pareseSystemImage(String systenImage) {
        return "http://ctimg.mg3721.com/upload/images/headportrait/public/" + systenImage + ".png";
    }


    public static void downFileFromWeb(Context context, String url, String fileName) {
        DownloadManager dManager = (DownloadManager)
                context.getSystemService(Context.DOWNLOAD_SERVICE);

        Uri uri = Uri.parse(url);

        DownloadManager.Request request = new DownloadManager.Request(uri);

        // 设置下载路径和文件名

        request.setDestinationInExternalPublicDir("download", fileName);

        request.setDescription("正在下载");

        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        request.setMimeType("application/vnd.android.package-archive");

        // 设置为可被媒体扫描器找到

        request.allowScanningByMediaScanner();

        // 设置为可见和可管理

        request.setVisibleInDownloadsUi(true);

        long refernece = dManager.enqueue(request);

        // 把当前下载的ID保存起来

        SharedPreferences sPreferences = context.getSharedPreferences("downloadplato", 0);

        sPreferences.edit().putLong("plato", refernece).commit();

    }

    public static long getDirSize(File file) {
        if (file == null) {
            return 0;
        }
        try {
            //判断文件是否存在
            if (file.exists()) {
                //如果是目录则递归计算其内容的总大小
                if (file.isDirectory()) {
                    File[] children = file.listFiles();
                    long size = 0;
                    if (children == null) {
                        return size;
                    }
                    for (File f : children)
                        size += getDirSize(f);
                    return size;
                } else {//如果是文件则直接返回其大小,以“兆”为单位
                    return file.length();
                }
            } else {
                System.out.println("文件或者文件夹不存在，请检查路径是否正确！");
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // 获取当前路径，可用空间
    public static long getAvailableSize(String path) {
        try {
            File base = new File(path);
            StatFs stat = new StatFs(base.getPath());
            long nAvailableCount = stat.getBlockSize()
                    * ((long) stat.getAvailableBlocks());
            return nAvailableCount;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 检测是否有可用空间
     *
     * @return
     */
    public static boolean isStorageSatisfied(Context context, DownLoadTaskTable downloadTask, boolean isUnZip) {

        String homePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        long size = getAvailableSize(homePath);
        if (isUnZip) {
            if (size < downloadTask.getUnzip_size()) {
                ToastUtils.getInstance(context).showToastSystem("内存空间不足");
            }
        } else {
            if (size < downloadTask.getTotalSize()) {
                ToastUtils.getInstance(context).showToastSystem("内存空间不足");
            }
        }


        return true;
    }

    public static void setButnStatus(TextView mgListviewItemInstall, int status, String gameId) {
        mgListviewItemInstall.setEnabled(true);
        mgListviewItemInstall.setTextColor(Color.parseColor("#43BEFE"));
        boolean needPay = false;
        if (status == 3 && !needPay) {
            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_pre_download));
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_normal_butn);
        } else if (status == 2 && !needPay) {
            mgListviewItemInstall.setText("即将开放");
            mgListviewItemInstall.setTextColor(0xff999999);
            mgListviewItemInstall.setEnabled(false);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutton_cannot_click);
        } else {
            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_download));
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_normal_butn);
        }
    }

    public static void setButnStatusBig(TextView mgListviewItemInstall, int status) {
        mgListviewItemInstall.setEnabled(true);
        boolean needPay = false;
        if (status == 3 && !needPay) {
            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_pre_download));
            mgListviewItemInstall.setTextColor(0xffffffff);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_big_normal_butn);
        } else if (status == 2 && !needPay) {
            mgListviewItemInstall.setText("即将开放");
            mgListviewItemInstall.setTextColor(0xff999999);
            mgListviewItemInstall.setEnabled(false);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutton_cannot_click);
        } else {
            mgListviewItemInstall.setText("立即下载");
            mgListviewItemInstall.setBackgroundResource(R.drawable.installbutn_big_normal_butn);
            mgListviewItemInstall.setTextColor(Color.WHITE);
        }
    }

    public static void setButnStatusGamedetial(TextView mgListviewItemInstall, int status) {
        mgListviewItemInstall.setEnabled(true);
        boolean needPay = false;
        if (status == 3 && !needPay) {
            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_pre_download));
            mgListviewItemInstall.setTextColor(0xffffffff);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_detial_normal_butn);
        } else if (status == 2 && !needPay) {
            mgListviewItemInstall.setText("即将开放");
            mgListviewItemInstall.setTextColor(0xff999999);
            mgListviewItemInstall.setEnabled(false);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutton_cannot_click);
        } else {
            mgListviewItemInstall.setText("立即下载");
            mgListviewItemInstall.setBackgroundResource(R.drawable.installbutn_detial_normal_butn);
            mgListviewItemInstall.setTextColor(Color.WHITE);
        }
    }

    public static void setButnStatusGamedetial(TextView mgListviewItemInstall, int status, int fromId) {
        mgListviewItemInstall.setEnabled(true);
        boolean needPay = false;
        if (status == 3 && !needPay) {
            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_pre_download));
            mgListviewItemInstall.setTextColor(0xffffffff);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_detial_normal_butn);
        } else if (status == 2 && !needPay) {
            mgListviewItemInstall.setText("即将开放");
            mgListviewItemInstall.setTextColor(0xff999999);
            mgListviewItemInstall.setEnabled(false);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutton_cannot_click);
        } else {
            mgListviewItemInstall.setText("立即下载");
            if (fromId==1) {
                mgListviewItemInstall.setBackgroundResource(R.drawable.installbutn_detial_normal_two_butn);
            } else {
                mgListviewItemInstall.setBackgroundResource(R.drawable.installbutn_detial_normal_butn);
            }
            mgListviewItemInstall.setTextColor(Color.WHITE);
        }
    }

    public static void setIndexButnStatusGamedetial(TextView mgListviewItemInstall, int status) {
        mgListviewItemInstall.setEnabled(true);
        boolean needPay = false;
        if (status == 3 && !needPay) {
            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_pre_download));
            mgListviewItemInstall.setTextColor(0xffffffff);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_detial_normal_index_butn);
        } else if (status == 2 && !needPay) {
            mgListviewItemInstall.setText("即将开放");
            mgListviewItemInstall.setTextColor(0xff999999);
            mgListviewItemInstall.setEnabled(false);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutton_cannot_click);
        } else {
            mgListviewItemInstall.setText("秒装");
            mgListviewItemInstall.setBackgroundResource(R.drawable.installbutn_detial_normal_index_butn);
            mgListviewItemInstall.setTextColor(Color.WHITE);
        }
    }

    public static void setButnStatus(TextView mgListviewItemInstall, RelativeLayout rLayoutRight, int status, String gameId) {
        //前面一步一定要检查 UtilsMy.checkPayTagInfo
        rLayoutRight.setEnabled(true);
        mgListviewItemInstall.setTextColor(0xff3CA4FD);
//        boolean needPay = checkPayTagInfo(payTagInfo, gameId) > 0;
        boolean needPay = false;
        if (status == 3 && !needPay) {

            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_pre_download));
            mgListviewItemInstall.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            mgListviewItemInstall.setTextColor(0xff3CA4FD);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_normal_butn);
        } else if (status == 2 && !needPay) {
            mgListviewItemInstall.setText("即将开放");
            mgListviewItemInstall.setTextSize(TypedValue.COMPLEX_UNIT_PX, mgListviewItemInstall.getContext().getResources().getDimensionPixelSize(R.dimen.wdp22));
            mgListviewItemInstall.setTextColor(0xff898989);
            rLayoutRight.setEnabled(false);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.recom_grey_butn);
        } else {

//            if (payTagInfo != null && payTagInfo.getAmount_check() > 0) {
//                mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.pay_game_amount, payTagInfo.getPayGameAmount()));
//            } else
            mgListviewItemInstall.setText(mgListviewItemInstall.getResources().getString(R.string.download_status_download));
            mgListviewItemInstall.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            mgListviewItemInstall.setTextColor(0xff3CA4FD);
            mgListviewItemInstall
                    .setBackgroundResource(R.drawable.installbutn_normal_butn);
        }
    }

    public static void starServiceDownGame(Context context, String gameID) {
        Intent intent = new Intent(context, ChWService.class);
        intent.putExtra("downGameId", gameID);
        MyJobIntentService.enqueueWork(context, intent);
    }

    public static void addTipsInView(List<GameTagInfoBean> tipBeans, LinearLayout view, Context context) {
        try {
            if (tipBeans == null) return;
            view.removeAllViews();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, context.getResources().getDimensionPixelOffset(R.dimen.wdp30));
            params.setMargins(0, 0, (int) context.getResources().getDimension(R.dimen.wdp9), 0);
            int i = 0;
            for (GameTagInfoBean tipBean : tipBeans) {
                i++;
                if (i > 4) return;
                TextView tip = new TextView(context);
                tip.setLayoutParams(params);
                tip.setGravity(Gravity.CENTER);
                tip.setText(tipBean.getName() + "");
//            tip.setBackgroundColor(Color.parseColor(tipBean.getColor()));@dimen/main_detial_textsize
                tip.setTextColor(Color.parseColor("#7A7A7A"));
//                    tip.setTextColor(Color.parseColor(tipBean.getColor()));
                tip.setPadding((int) context.getResources().getDimension(R.dimen.wdp12), 0, (int) context.getResources().getDimension(R.dimen.wdp12), 0);
                tip.setSingleLine(true);
//            tip.setTextSize(context.getResources().getDimensionPixelOffset(R.dimen.main_detial_textsize));
//                tip.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.main_detial_textsize));
//                tip.setTextSize(9);
                tip.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.wdp18));
//                    tip.setTextSize(9);
                tip.setBackgroundResource(R.drawable.game_detial_tip_back);
//                    tip.setBackgroundDrawable(TipViewUtil.getDrawableUseColor(context, tipBean.getColor() + ""));
                view.addView(tip);


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setIconImage(final Context context, String imageSrc, final SimpleDraweeView userIcon) {
        if (StringUtils.isEmpty(imageSrc.trim()) || userIcon == null) {
            imageSrc = "http://ctimg.mg3721.com/upload/images/headportrait/public/system_1.png";
        }

        MyImageLoader.loadUserIcon(userIcon, R.drawable.main_normal_user_icon, imageSrc);
    }

    /**
     * 复制到系统剪贴板
     *
     * @param context
     * @param s
     */
    public static void copyToClickBoard(Context context, String s) {
        if (context == null) return;

        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(s);

        ToastUtils.getInstance(context).showToastSystem("复制成功");
    }

//    public static void addTipsInView(int down_count, String appSize, TipNew showTip, LinearLayout view, Context context) {
//        if (StringUtils.isEmpty(appSize)) {
//            appSize = "1";
//        }
//        view.removeAllViews();
//        View viewAdd = LayoutInflater.from(context).inflate(R.layout.appitem_appsize_downcount_layout, null);
//        TextView appdownCount = (TextView) viewAdd.findViewById(R.id.appdownCount);
//        TextView appsizeText = (TextView) viewAdd.findViewById(R.id.appsize);
//        TextView appType = (TextView) viewAdd.findViewById(R.id.appType);
//        TextView tongban = (TextView) viewAdd.findViewById(R.id.tongban);
//        appdownCount.setText(StringUtils.formatNumberShort999(down_count));
//        long appSizeLong = (long) (1024 * 1024 * Double.parseDouble(appSize));
//        appsizeText.setText(UtilsMy.roundFileSize(appSizeLong));
//        if (showTip != null) {
//            if (showTip.getModel() != null) {
//                appType.setText(showTip.getModel().getName());
//            } else {
//                appType.setVisibility(View.GONE);
//            }
//        } else {
//            appType.setVisibility(View.GONE);
//            tongban.setVisibility(View.GONE);
//        }
//        view.addView(viewAdd);
//    }


    /**
     * 正方形
     *
     * @param context
     * @param imageSrc
     * @param userIcon
     */
    public static void setNetMatchIconImageRET(final Context context, String imageSrc, SimpleDraweeView userIcon) {
        if (userIcon == null) return;
        Context ctx = userIcon.getContext();
        if (imageSrc == null) {
            MyImageLoader.load(userIcon, R.mipmap.net_match_default_user_icon, MyImageLoader.makeUri(ctx, R.mipmap.net_match_default_user_icon).toString());
            return;
        }
        MyImageLoader.loadUserIcon(userIcon, R.mipmap.net_match_default_user_icon, imageSrc);
    }

    /**
     * 设置推荐商品
     */
    public static void setRecommendGoods(final Activity activity, final ConvenientBanner vp_recommend
            , final List<JumpBaseBean> data, final boolean isAuto) {
        if (vp_recommend==null || data==null) return;
        //设置如果只有一组数据时不能滑动
//        vp_recommend.setManualPageable(data.size() == 1 ? false : true);
//        vp_recommend.setCanLoop(data.size() == 1 ? false : true);
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        vp_recommend.setPages(new CBViewHolderCreator() {
            @Override
            public NetworkImageHolderView createHolder(View itemView) {
                return new NetworkImageHolderView(itemView, activity);
            }

            @Override
            public int getLayoutId() {
                return R.layout.item_banner_view;
            }
        }, data)
          //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
         .setPageIndicator(new int[]{R.drawable.shape_item_index_white, R.drawable.shape_item_index_red})
         //设置指示器的方向
         .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);

        if (isAuto) {
            vp_recommend.startTurning(4000);
            vp_recommend.setOnPageChangeListener(new OnPageChangeListener() {
                int newS;
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    newS = newState;
                    LogUtils.e("tbl>>>newState:"+newState);
//                    if (newState==0 && isAuto) {
//                        MyApplication.bannerPo = vp_recommend.getCurrentItem();
//                    }
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                }

                @Override
                public void onPageSelected(int index) {
                    LogUtils.e("tbl>>>index:"+index);
                    if (newS==0 && isAuto) {
                        LogUtils.e("tbl>>>index:"+index+",newS:"+newS);
                        MyApplication.bannerPo = vp_recommend.getCurrentItem();
                        MyApplication.bannerTime = System.currentTimeMillis();
                        vp_recommend.startTurning(4000);
                    }
                }
            });
        }
        vp_recommend.post(new Runnable() {
            @Override
            public void run() {
                vp_recommend.setCurrentItem(MyApplication.bannerPo, false);
            }
        });
    }

}
